/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * telaPrincipal.java
 *
 * Created on 15/10/2009, 20:16:33
 */
package Interface;

import estados.Estados;
import java.awt.Color;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author linton
 */
public class telaPrincipal extends javax.swing.JFrame {

    private Estados estados;
    private int pid = 1240;
    private int vid = 63;

    /** Creates new form telaPrincipal */
    public telaPrincipal() {
        initComponents();
        double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
        double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
        double widthf = getWidth() / 2;
        double heigthf = getHeight() / 2;
        int widthFinal = (int) (width - widthf);
        int heigthFinal = (int) (height - heigthf);
        setLocation(widthFinal, heigthFinal);
        
        this.pid = 1240;
        this.vid = 63;

        
        estados = new Estados();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jToggleButton1 = new javax.swing.JToggleButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        textArea1 = new java.awt.TextArea();
        jButton1 = new javax.swing.JButton();
        num_conv = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        gravar_memoria = new javax.swing.JButton();
        ler_memoria = new javax.swing.JButton();
        endereco = new javax.swing.JTextField();
        dado = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Modulo Gerenciamento")));

        jToggleButton1.setForeground(new java.awt.Color(255, 0, 0));
        jToggleButton1.setText("Conectar");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Piscar Led");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Verificar Botão");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Converter");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton1.setText("Ficar Convertendo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        num_conv.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        num_conv.setText("10");

        jLabel1.setText("X");

        gravar_memoria.setText("Gravar Memoria");
        gravar_memoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gravar_memoriaActionPerformed(evt);
            }
        });

        ler_memoria.setText("Ler Memoria");
        ler_memoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ler_memoriaActionPerformed(evt);
            }
        });

        endereco.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        endereco.setText("0");
        endereco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enderecoActionPerformed(evt);
            }
        });

        dado.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        dado.setText("b");

        jLabel2.setText("Endereco");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jToggleButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addGap(34, 34, 34)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(ler_memoria, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(gravar_memoria, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(dado, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(endereco, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(num_conv, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 446, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(91, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jToggleButton1)
                    .addComponent(ler_memoria)
                    .addComponent(endereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(gravar_memoria)
                    .addComponent(dado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(num_conv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButton4)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (estados.isConectado()) {
            try {
                estados.piscarLed();
            } catch (InterruptedException ex) {
                Logger.getLogger(telaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            textArea1.insert("\nDispositivo não está conectado", textArea1.getSelectionStart());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (estados.isConectado()) {
            if (estados.verificarBotao() == 0) {
                textArea1.insert("\nBotão está pressionado", textArea1.getSelectionStart());
            } else {
                textArea1.insert("\nBotão não está pressionado", textArea1.getSelectionStart());
            }
        } else {
            textArea1.insert("\nDispositivo não está conectado", textArea1.getSelectionStart());
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        if (estados.isConectado()) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException ex) {
                Logger.getLogger(telaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
            String resultado = String.valueOf(estados.converter());
            textArea1.insert("\n" + resultado, textArea1.getSelectionStart());
        } else {
            textArea1.insert("\nDispositivo não está conectado", textArea1.getSelectionStart());
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        // TODO add your handling code here:
         if (estados.inicar(pid, vid) == true) {
            textArea1.insert("\nDispositivo ENCONTRADO e CONECTADO", textArea1.getSelectionStart());
            jToggleButton1.setSelected(true);
            jToggleButton1.setText("Conectado");
            jToggleButton1.setForeground(Color.blue);
            estados.verificaConexao(pid, vid, jToggleButton1, textArea1);
        } else {
            textArea1.insert("\nDispositivo não encontrado", textArea1.getSelectionStart());
            jToggleButton1.setSelected(false);
            jToggleButton1.setText("Conectar");
            jToggleButton1.setForeground(Color.RED);
        }
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        double i=0;
        while(estados.isConectado() && i<Integer.parseInt(num_conv.getText())){
        
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Logger.getLogger(telaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
            String resultado = String.valueOf(estados.converter());
            textArea1.insert("\n" + resultado, textArea1.getSelectionStart());
            
            i++;
        }
        
        if (!estados.isConectado())
            textArea1.insert("\nDispositivo não está conectado", textArea1.getSelectionStart());
        else
            textArea1.insert("\ntotal de erros para "+i+" conversões: "+(int)estados.getErrosCont()+"\nPorcentagem de erros: "+estados.getErrosCont()*100/i+"%", textArea1.getSelectionStart());
            estados.setErrosCont(0);


    }//GEN-LAST:event_jButton1ActionPerformed

    private void gravar_memoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gravar_memoriaActionPerformed
        // TODO add your handling code here:
        if (estados.isConectado()){
            
//            estados.gravarMemoria('a','a');
            if(estados.gravarMemoria(dado.getText().charAt(0),endereco.getText().charAt(0)))
                textArea1.insert("\nO dado "+dado.getText().charAt(0)+" foi gravado no endereco "+ endereco.getText().charAt(0), textArea1.getSelectionStart());
            else
                textArea1.insert("\nErro na gravacao", textArea1.getSelectionStart());
        }
    }//GEN-LAST:event_gravar_memoriaActionPerformed

    private void ler_memoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ler_memoriaActionPerformed
        // TODO add your handling code here:
         if (estados.isConectado()){
            try {
                //estados.lerMemoria(2);
                textArea1.insert("\nDado "+estados.lerMemoria(endereco.getText().charAt(0))+" lido no endereco "
                        +endereco.getText().charAt(0), textArea1.getSelectionStart());
            } catch (InterruptedException ex) {
                Logger.getLogger(telaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
            
         }
    }//GEN-LAST:event_ler_memoriaActionPerformed

    private void enderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enderecoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_enderecoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new telaPrincipal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dado;
    private javax.swing.JTextField endereco;
    private javax.swing.JButton gravar_memoria;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JButton ler_memoria;
    private javax.swing.JTextField num_conv;
    private java.awt.TextArea textArea1;
    // End of variables declaration//GEN-END:variables
}
